# -*- coding: utf-8 -*-
import sys
import os
import shlex, subprocess
import re

os.umask(0000)

def escapeshellarg(arg):
    return '\'' + arg.replace('\'', '\'' + '\\' + '\'' + '\'') + '\''

# ----------------------------------------------------------------------------------
# Dịch code lua
# ----------------------------------------------------------------------------------
def getInfo(mp3File):
    if not os.path.exists(mp3File): return 0
    img_cmd = '/usr/bin/ffmpeg '

    command = img_cmd + ' -i ' + escapeshellarg(mp3File)
    print 'getInfo: ', mp3File, "\n", command

    args = shlex.split(str(command))
    process = subprocess.Popen(args, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    process.wait()
    output = process.communicate()
    if output!='':
        matches = re.search(r'Duration: (\d+):(\d+):([\d\.]+),', output[1])
        if matches!=None:
            return int(1000*(float(matches.group(3)) + 60*int(matches.group(2)) + 60*60*int(matches.group(1))))

    return 0

def convert2Amr(mp3File):
    if not os.path.exists(mp3File): return 0
    dest = mp3File+".c.amr" 
    mime_type = "audio/amr"
    option = "-y -ac 1 -ar 8000 -ab 12.2k"
    command = "ffmpeg -i '"+mp3File+"' "+option+" '"+dest+"'" 
    print 'convert2Amr: ', mp3File, "\n", command
    if (dest==''): return 0
    if not os.path.exists(dest) or getInfo(dest)==0:
      args = shlex.split(str(command))
      process = subprocess.Popen(args, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      process.wait()
      output = process.communicate()
      if output!='':
         d1 = getInfo(mp3File)
         d2 = getInfo(dest)
         if d1!=d2:
            print 'ERR: ', mp3File
            with open("/home/tmp/errorlogConvertMp3.txt", "a") as f:
              f.write(mp3File+"\n")
              f.close()
    return 1
#print getInfo('/home/hoangnamhai/python-gearman/web/uploads/music/0/0/1/3/933ea25fa0470307546e77738cc8.mp3')
